
var AV = require('leanengine');
var tribeRedis = require( './tribeRedis' );
var apis = require( './lib/apis' );
var keys = require( './lib/keys' );
var group = require( './lib/group' );
var message = require( './lib/message' );
var redisServer = require( './redis/redisServer' );
var qiniuServer = require( './server/qiniuServer' );
var common = require( './common' );
var async = require( "async" );
var rongrequest = require( './lib/rongrequest' );
rongrequest.init(apis['rongyun']['Key'], apis['rongyun']['Secret']);
/**
 * 部落保存后，生成部落二维码
 */
AV.Cloud.afterSave('Tribe', function (request) {
  // console.log("redis----");
  console.log('afterSaveTribe');
  if (request.object.get("tribeAvator")) {
    var url = request.object.get("tribeAvator").thumbnailURL(110, 110);
    var qrAPI = "https://leancloud.cn/1.1/qrcode?url=" + apis['common']['downUrl'] + "?tId=" + request.object.id + "&width=600&height=600";
    qiniuServer.getQrcodeUrl("tribe_qrCode_" + request.object.id + new Date().getTime() + ".jpg", qrAPI, function (err, newQrCode) {
      if (!err) {
        var File = common.getEntity("_File");
        var file = new File();
        file.set("url", apis['qiniu']['url'] + "/" + newQrCode + "?watermark/1/image/" + new Buffer(url).toString('base64').replace(new RegExp(/(\+)/g), '-').replace(new RegExp(/(\/)/g), '_') + "/gravity/Center/dx/0/dy/0");
        file.set("name", "tribe_qrCode_" + request.object.id + new Date().getTime());
        file.save().then(function (filec) {
          request.object.set("qrCode", filec);
          // console.log(JSON.stringify(filec));
          request.object.save();
        },function (error) {
          console.log(JSON.stringify(error));
        })
      } else {
        console.log(JSON.stringify(err));
      }
    });
  }

  //将部落信息存入redis
  redisServer.addRedisContent("tribe_" + request.object.id, request.object, null, function (err, result) {

  })
});
AV.Cloud.afterUpdate('Tribe', function(request) {

  // console.log("1111")
  console.log('afterUpdateTribe');
  if(request.object.get("_updatedKeys")!=null && request.object.get("_updatedKeys").indexOf("tribeAvator")>-1&&request.object.get("tribeAvator")){


    var url = request.object.get("tribeAvator").thumbnailURL(110, 110);
    var qrAPI="https://leancloud.cn/1.1/qrcode?url="+apis['common']['downUrl']+"?tId="+request.object.id+"&width=600&height=600";
    qiniuServer.getQrcodeUrl("tribe_qrCode_"+request.object.id+new Date().getTime()+".jpg",qrAPI,function(err,newQrCode){
      if(!err){
        var File = common.getEntity("_File");
        var file=new File();
        file.set("url",apis['qiniu']['url'] + "/"+newQrCode+"?watermark/1/image/"+new Buffer(url).toString('base64').replace(new RegExp(/(\+)/g),'-').replace(new RegExp(/(\/)/g),'_')+"/gravity/Center/dx/0/dy/0");
        //file.set("url",apis['qiniu']['url'] + "/"+newQrCode+"?"+common.getQrCodeFormat(request.object));
        file.set("name","tribe_qrCode_"+request.object.id+new Date().getTime());
        file.save(null,{
          success: function(file) {
            request.object.set("qrCode",file);
            request.object.save();
          }
        })
      }
    });
  }

  if(request.object.get("_updatedKeys")!=null){
    if(request.object.get("_updatedKeys").indexOf("status")>-1){
      if(request.object.get("status")=="1"){
        redisServer.addRedisContent("tribe_"+request.object.id,request.object,null,function(err,result){});
        tribeRedis.updateTribeMemberNum(request.object.get("memberNum"),request.object.get("postNum"),request.object.id);
      }else{
        redisServer.delRedisContent("tribe_"+request.object.id,function(err,result){});
        tribeRedis.updateTribeMemberNum(request.object.get("memberNum"),request.object.get("postNum"),request.object.id);
        redisServer.delRedisContent(keys["tribe"]+request.object.id,function(err,result){});
      }
    }else{
      redisServer.addRedisContent("tribe_"+request.object.id,request.object,null,function(err,result){});
      tribeRedis.updateTribeMemberNum(request.object.get("memberNum"),request.object.get("postNum"),request.object.id);
    }

    if(request.object.get("status")=="1"){
      var tribeInfo = {};

      var tribeObj = request.object;
      tribeOId = tribeObj.id;
      tribeInfo[keys['tribeFeild']['id']] = tribeOId;
      if(tribeObj.get('name')){
        tribeInfo[keys['tribeFeild']['name']] = tribeObj.get('name');
      }else{
        tribeInfo[keys['tribeFeild']['name']] = '';
      }
      if(tribeObj.get('tribeAvator')){
        tribeInfo[keys['tribeFeild']['tribeAvator']] = JSON.parse(JSON.stringify(tribeObj.get('tribeAvator'))).url;
      }else {
        tribeInfo[keys['tribeFeild']['tribeAvator']] = '';
      }
      if( tribeObj.get('memberNum')){
        tribeInfo[keys['tribeFeild']['memberNum']] = tribeObj.get('memberNum');
      }else{
        tribeInfo[keys['tribeFeild']['memberNum']] = 0;
      }
      if( tribeObj.get('postNum')){
        tribeInfo[keys['tribeFeild']['postNum']] = tribeObj.get('postNum');
      }else{
        tribeInfo[keys['tribeFeild']['postNum']] =  0;
      }
      if( tribeObj.get('introduction')){
        tribeInfo[keys['tribeFeild']['introduction']] = tribeObj.get('introduction');
      }else{
        tribeInfo[keys['tribeFeild']['introduction']] =  "";
      }
      //部落详情放入redis hsahs 中
      redisServer.hmset(keys["tribe"]+tribeOId,tribeInfo,function(err,rs){});
    }
  }
});

AV.Cloud.beforeSave('TribeMember', function(request, response) {
  console.log('beforeSaveTribeMember');
  if(request.object.get('mySortNo') == null || request.object.get('mySortNo') == undefined) {
    //保存mySortNo
    var query = new AV.Query('TribeMember');
    if (request.object.get("joinType") != "2") {
      query.descending("mySortNo");
    } else {
      query.ascending("mySortNo");
    }
    query.equalTo("userOId", request.object.get("userOId"));
    query.first().then(function (tribeMemberObj) {
      if (tribeMemberObj != null) {
        if (request.object.get("joinType") != "2")
          request.object.set("mySortNo", parseInt(tribeMemberObj.get("mySortNo") + 1));
        else
          request.object.set("mySortNo", parseInt(tribeMemberObj.get("mySortNo") - 1));
      } else {
        request.object.set("mySortNo", 1);
      }
      request.object.set("postNum", 0);
      return response.success();
    },function (error) {
      return response.success();
    });
  } else
    return response.success();
});

//部落成员关系afterSave事件
AV.Cloud.afterSave('TribeMember', function(request) {
  console.log('afterSaveTribeMember');
  var userOId=request.object.get("userOId");
  var objectId=request.object.id;
  var tribeOId=request.object.get("tribeOId");
  var handler=request.object.get("handler");//操作人
  if(request.object.get("userType")=="0"||request.object.get("userType")=="-1"){
    //同步到融云
    group.quit(userOId,tribeOId,"json",function(err,result){
      if(err){
        request.object.set("rongyunStatus","0");
        request.object.save();
      }else{
        //插入退出日志
        var RongyunLog=common.getEntity("RongyunLog");
        var rongyunLog=new RongyunLog();
        rongyunLog.set("type","quit");
        rongyunLog.set("userOId",userOId);
        rongyunLog.set("tribeOId",tribeOId);
        rongyunLog.set("handler",handler);
        rongyunLog.save();
      }
    })
  }else{
    if(request.object.get("userType")=="1"){
      //同步到融云
      group.create(userOId,tribeOId,"","json",function(err,result){
        if(err){
          request.object.set("rongyunStatus","0");
          request.object.save();
        }
      });
    }else{
      //同步到融云
      group.join(userOId,tribeOId,"","json",function(err,result){
        if(err){
          request.object.set("rongyunStatus","0");
          request.object.save();
        }else{
          //向后台推送一个消息已加入的消息
          joinTribePush(tribeOId,userOId,function(err,result){
            console.log('joinTribePush');
            if(err){
              request.object.set("rongyunStatus","0");
              request.object.save();
            }
          })
        }
      });
    }
  }
  //向用户表保存已加入部落
  var userObj = AV.Object.createWithoutData('User', userOId);
  userObj.fetch({
    success: function(userObj) {
      if(userObj!=null){
        var relation = userObj.relation('tribes');
        //拉黑或退出则移除
        if(["-1","0"].indexOf(request.object.get("userType"))>-1){
          relation.remove(request.object);
        }else{
          relation.add(request.object);
        }
        userObj.save();
      }
    }
  })

  var tribeInfo = {};


  redisServer.sadd(keys['userTribe'] + userOId, tribeOId,function(error,res){});

  var query = new AV.Query('Tribe');
  query.equalTo("objectId",tribeOId);
  query.first().then(function(tribeObj){
    tribeInfo[keys['tribeFeild']['id']] = tribeOId;
    if(tribeObj.get('name')){
      tribeInfo[keys['tribeFeild']['name']] = tribeObj.get('name');
    }else{
      tribeInfo[keys['tribeFeild']['name']] = '';
    }
    if(tribeObj.get('tribeAvator')){
      tribeInfo[keys['tribeFeild']['tribeAvator']] = JSON.parse(JSON.stringify(tribeObj.get('tribeAvator'))).url;
    }else {
      tribeInfo[keys['tribeFeild']['tribeAvator']] = '';
    }
    if( tribeObj.get('memberNum')){
      tribeInfo[keys['tribeFeild']['memberNum']] = tribeObj.get('memberNum');
    }else{
      tribeInfo[keys['tribeFeild']['memberNum']] = 0;
    }
    if( tribeObj.get('postNum')){
      tribeInfo[keys['tribeFeild']['postNum']] = tribeObj.get('postNum');
    }else{
      tribeInfo[keys['tribeFeild']['postNum']] =  0;
    }
    if( tribeObj.get('introduction')){
      tribeInfo[keys['tribeFeild']['introduction']] = tribeObj.get('introduction');
    }else{
      tribeInfo[keys['tribeFeild']['introduction']] =  "";
    }
    if(request.object.get('isTop')){
      tribeInfo[keys['tribeFeild']['isTop']] = request.object.get('isTop');
      redisServer.addRedisContent(keys['userTribeTop']+userOId+"_"+tribeInfo.id,request.object.get('isTop'),null,function(error,top){});

    }else{
      tribeInfo[keys['tribeFeild']['isTop']] = 0;
      redisServer.addRedisContent(keys['userTribeTop']+userOId+"_"+tribeInfo.id,0,null,function(error,top){});

    }

    if(request.object.get('mySortNo')){
      redisServer.addRedisContent(keys['userTribeSort']+userOId+"_"+tribeInfo.id,request.object.get('mySortNo'),null,function(error,top){});
    }else{
      redisServer.addRedisContent(keys['userTribeSort']+userOId+"_"+tribeInfo.id,0,null,function(error,top){});
    }


    if(request.object.get('userType')){
      redisServer.addRedisContent(keys['userTribeType']+userOId+"_"+tribeInfo.id,request.object.get('userType'),null,function(error,top){});
    }else{
      redisServer.addRedisContent(keys['userTribeType']+userOId+"_"+tribeInfo.id,3,null,function(error,top){});
    }
    if(request.object.get('infocenterCount')){
      redisServer.addRedisContent(keys['msg']+tribeInfo.id+"_"+userOId,request.object.get('infocenterCount'),null,function(erro,msgNum){});
    }else{
      redisServer.addRedisContent(keys['msg']+tribeInfo.id+"_"+userOId,0,null,function(erro,msgNum){});
    }
    //部落详情放入redis hsahs 中
    redisServer.hmset(keys["tribe"]+tribeOId,tribeInfo,function(err,rs){});
  },function(err){});

});
function joinTribePush(tribeOId,userOId,callback){
  var oj={};
  var tj={};
  tj["content"]="！";
  tj["sourceType"]="";
  tj["fromOId"]="";
  tj["objectId"]="";
  tj["tribeOId"]=tribeOId;
  oj["extra"]="1010";
  oj["content"]=tj;
  oj["code"]="1";
  //新版本推送添加好友请求
  var sendObj={};
  sendObj["operation"]="";
  sendObj["sourceUserId"]="";
  sendObj["targetUserId"]="";
  sendObj["extra"]=tribeOId;
  var base64Content=new Buffer(JSON.stringify(oj)).toString('base64');
  base64Content=base64Content.replace(/\+/g,"@");
  base64Content=base64Content.replace(/\=/g,"");
  sendObj["extra"]=base64Content;
  message.publish("admin",userOId,"RC:ContactNtf",JSON.stringify(sendObj),"json", function(err,result) {
    return callback(err,result);
  });
}
//部落成员关系afterUpdate事件
AV.Cloud.afterUpdate('TribeMember', function(request) {
  console.log('afterUpdateTribeMember');
  // console.log(request.object.get("tribeOId"));
  // console.log(request.object.get("userOId"));
  // console.log(request.object.get("infocenterCount"));
  // console.log(request.object.get("infocenterCount"));
  redisServer.addRedisContent(keys["msg"]+request.object.get("tribeOId")+"_"+request.object.get("userOId"),0,null,function(err,obj){
  });
  if(request.object.get("_updatedKeys")!=null){
    if(request.object.get("_updatedKeys").indexOf("userType")>-1){
      var userOId=request.object.get("userOId");
      var tribeOId=request.object.get("tribeOId");
      var handler=request.object.get("handler");//操作人
      if(request.object.get("userType")=="0"||request.object.get("userType")=="-1"){
              redisServer.srem(keys['userTribe'] + userOId, tribeOId,function(error,res){});
          //同步到融云
        group.quit(userOId,tribeOId,"json",function(err,result){
          if(err){
            request.object.set("rongyunStatus","0");
            request.object.save();
          }else{
            //插入退出日志
            var RongyunLog=common.getEntity("RongyunLog");
            var rongyunLog=new RongyunLog();
            rongyunLog.set("type","quit");
            rongyunLog.set("userOId",userOId);
            rongyunLog.set("tribeOId",tribeOId);
            rongyunLog.set("handler",handler);
            rongyunLog.save();
          }
        })
      }else{

        var tribeInfo = {};
        redisServer.sadd(keys['userTribe'] + userOId, tribeOId,function(error,res){});
        var query = new AV.Query('Tribe');
        query.equalTo("objectId",tribeOId);
        query.first().then(function(tribeObj){
          tribeInfo[keys['tribeFeild']['id']] = tribeOId;
          if(tribeObj.get('name')){
            tribeInfo[keys['tribeFeild']['name']] = tribeObj.get('name');
          }else{
            tribeInfo[keys['tribeFeild']['name']] = '';
          }
          if(tribeObj.get('tribeAvator')){
            tribeInfo[keys['tribeFeild']['tribeAvator']] = JSON.parse(JSON.stringify(tribeObj.get('tribeAvator'))).url;
          }else {
            tribeInfo[keys['tribeFeild']['tribeAvator']] = '';
          }
          if( tribeObj.get('memberNum')){
            tribeInfo[keys['tribeFeild']['memberNum']] = tribeObj.get('memberNum');
          }else{
            tribeInfo[keys['tribeFeild']['memberNum']] = 0;
          }
          if( tribeObj.get('postNum')){
            tribeInfo[keys['tribeFeild']['postNum']] = tribeObj.get('postNum');
          }else{
            tribeInfo[keys['tribeFeild']['postNum']] =  0;
          }
          if( tribeObj.get('introduction')){
            tribeInfo[keys['tribeFeild']['introduction']] = tribeObj.get('introduction');
          }else{
            tribeInfo[keys['tribeFeild']['introduction']] =  "";
          }
          if(request.object.get('isTop')){
            tribeInfo[keys['tribeFeild']['isTop']] = request.object.get('isTop');
            redisServer.addRedisContent(keys['userTribeTop']+userOId+"_"+tribeInfo.id,request.object.get('isTop'),null,function(error,top){});

          }else{
            tribeInfo[keys['tribeFeild']['isTop']] = 0;
            redisServer.addRedisContent(keys['userTribeTop']+userOId+"_"+tribeInfo.id,0,null,function(error,top){});

          }

          if(request.object.get('mySortNo')){
            redisServer.addRedisContent(keys['userTribeSort']+userOId+"_"+tribeInfo.id,request.object.get('mySortNo'),null,function(error,top){});
          }else{
            redisServer.addRedisContent(keys['userTribeSort']+userOId+"_"+tribeInfo.id,0,null,function(error,top){});
          }


          if(request.object.get('userType')){
            redisServer.addRedisContent(keys['userTribeType']+userOId+"_"+tribeInfo.id,request.object.get('userType'),null,function(error,top){});
          }else{
            redisServer.addRedisContent(keys['userTribeType']+userOId+"_"+tribeInfo.id,3,null,function(error,top){});
          }
          if(request.object.get('infocenterCount')){
            redisServer.addRedisContent(keys['msg']+tribeInfo.id+"_"+userOId,request.object.get('infocenterCount'),null,function(erro,msgNum){});
          }else{
            redisServer.addRedisContent(keys['msg']+tribeInfo.id+"_"+userOId,0,null,function(erro,msgNum){});
          }
          //部落详情放入redis hsahs 中
          redisServer.hmset(keys["tribe"]+tribeOId,tribeInfo,function(err,rs){});
        },function(err){
        });

        //同步到融云
        group.join(userOId,tribeOId,"群","json",function(err,result){
          if(err){
            request.object.set("rongyunStatus","0");
            request.object.save();
          }else{
            //向后台推送一个消息已加入的消息
            joinTribePush(tribeOId,userOId,function(err,result){
              if(err){
              }
            })
          }
        });
      }

      //向用户表保存已加入部落
      var userObj = AV.Object.createWithoutData('User', userOId);
      userObj.fetch().then(function (userObj) {
        if(userObj!=null){
          var relation = userObj.relation('tribes');
          //拉黑或退出则移除
          if(["-1","0"].indexOf(request.object.get("userType"))>-1){
            relation.remove(request.object);
          }else{
            relation.add(request.object);
          }
          userObj.save();
        }
      },function (error) {
        console.log(error);
      });
    }
  }
});

//用户退出部落监控事件
AV.Cloud.afterDelete('TribeMember', function(request) {
  console.log('afterDeleteTribeMember');
  var userOId=request.object.get("userOId");
  var tribeOId=request.object.get("tribeOId");
  var handler=request.object.get("handler");//操作人
  if(userOId!=null&&userOId!=undefined){
    if(request.object.get("userType")!="0"){
        redisServer.srem(keys['userTribe'] + userOId, tribeOId,function(error,res){});
      //同步到融云
      group.quit(userOId,tribeOId,"json",function(err,result){
        if(err){
        }else{
          //插入退出日志
          var RongyunLog=common.getEntity("RongyunLog");
          var rongyunLog=new RongyunLog();
          rongyunLog.set("type","quit");
          rongyunLog.set("userOId",userOId);
          rongyunLog.set("tribeOId",tribeOId);
          rongyunLog.set("handler",handler);
          rongyunLog.save();
        }
      })
      var query = new AV.Query('Tribe');
      query.equalTo("objectId", tribeOId);
      query.first(function (tribeObj) {
        if(tribeObj!=null){
          content="您已被管理员移除出群【"+tribeObj.get("name")+"】";
          if(userOId==handler)
            content="您已退出群【"+tribeObj.get("name")+"】";
          common.sendTextMsg("admin",userOId,content,function(err,result){
          })
        }
      },function (error) {
        console.log(error);
      });
    }
  }
  //向用户表保存已加入部落
  var userObj = AV.Object.createWithoutData('User', userOId);
  userObj.fetch({
    success: function(userObj) {
      if(userObj!=null){
        var relation = userObj.relation('tribes');
        //如果是拉黑则移除
        relation.remove(request.object);
        userObj.save();
      }
    }
  })
});